package org.example.xml;

import org.example.builder.BaseBuilder;
import org.example.config.Configuration;
import org.example.mapping.MappedStatement;
import org.example.mapping.SqlSource;

public class XMLStatementBuilder extends BaseBuilder {
    private final XNode node;
    private final String resource;

    private String namespace;

    public XMLStatementBuilder(Configuration configuration, XNode node,String resource,String namespace) {
        super(configuration);
        this.node = node;
        this.resource = resource;
        this.namespace = namespace;
    }

    //解析SQL
    public void parse() {
        //SQLID
        String id = namespace+"."+node.getStringAttribute("id");
        //SQL
        String sql = node.getBody();
        //参数类型
        String parameterType = node.getStringAttribute("parameterType");
        Class<?> parameterTypeClass = null == parameterType?Object.class:resolveClass(parameterType);
        //返回类型
        String resultType = node.getStringAttribute("resultType");
        Class<?> returnTypeClass = resolveClass(resultType);

        SqlSourceBuilder sqlSourceBuilder = new SqlSourceBuilder(configuration);
        Class<?> clazz = parameterType == null ? Object.class : parameterTypeClass;
        //SQL资源
        SqlSource sqlSource = sqlSourceBuilder.parse(sql, clazz);

        MappedStatement mappedStatement = new MappedStatement(
                id, resource,
                configuration,
                sqlSource,
                returnTypeClass,
                parameterTypeClass
        );
        configuration.setMappedStatement(mappedStatement);
    }
}
